package com.leshua.channel.mpos.network.handler;

import com.leshua.channel.mpos.common.utils.LeshuaXmlUtils;
import com.leshua.channel.mpos.service.pay.ScanPayService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author devlin
 * @version 1.0
 * @date 2020/4/23 16:05
 */
@Slf4j
@ChannelHandler.Sharable
@Component
public class ScanPayHandler extends ChannelInboundHandlerAdapter {


    @Resource
    private ScanPayService scanPayService;


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        String msgContent = in.toString(CharsetUtil.UTF_8);
        log.info("Server received: {}", msgContent);
        scanPayService.handle(ctx, msgContent);
        log.info("msg arr:{}", msgContent.getBytes());
        ctx.writeAndFlush(Unpooled.copiedBuffer("成功", CharsetUtil.UTF_8));
    }

    /**
     * 在读取操作期间，有异常抛出时会调用。
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        log.info("请求异常:{}", cause.getMessage());
        ctx.writeAndFlush(Unpooled.copiedBuffer(LeshuaXmlUtils.errorMsg("请求异常"), CharsetUtil.UTF_8));
        ctx.channel().close();
    }
}
